import React, { useState } from 'react';
import {
  Table,
  Button,
  Space,
  Image,
  Tag,
  Modal,
  message,
  Form,
  Input,
  Select,
  Card,
  Row,
  Col,
  Switch,
  InputNumber,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  ReloadOutlined,
  DragOutlined,
} from '@ant-design/icons';
import { useTable } from '@/hooks/useTable';
import type { ColumnsType } from 'antd/es/table';
import adminApi from '@/api/admin-api';

const { Option } = Select;
const { confirm } = Modal;

interface TopicItem {
  id: number;
  name: string;
  description?: string;
  icon?: string;
  color?: string;
  sort_order: number;
  status: 'enabled' | 'disabled';
  created_at: string;
  updated_at: string;
}

interface SearchForm {
  keyword?: string;
  status?: 'enabled' | 'disabled';
}

interface TopicForm {
  name: string;
  description?: string;
  icon?: string;
  color?: string;
  sort_order: number;
  status: 'enabled' | 'disabled';
}

const TopicList: React.FC = () => {
  const [searchForm] = Form.useForm();
  const [modalForm] = Form.useForm();
  const [searchParams, setSearchParams] = useState<SearchForm>({});
  const [modalVisible, setModalVisible] = useState(false);
  const [editingTopic, setEditingTopic] = useState<TopicItem | null>(null);
  const [modalLoading, setModalLoading] = useState(false);

  // 获取主题列表
  const fetchTopics = async (params: any) => {
    try {
      const response = await adminApi.topicManagement.adminTopics({
        page: params.current || 1,
        page_size: params.pageSize || 20,
        keyword: params.keyword,
        status: params.status,
      });
      
      return {
        list: response.data || [],
        total: response.total || 0,
      };
    } catch (error) {
      message.error('获取主题列表失败');
      return {
        list: [],
        total: 0,
      };
    }
  };

  const { data, loading, pagination, refresh, handleTableChange, handleSearch } = useTable({
    fetchData: fetchTopics,
    searchParams,
  });

  // 表格列配置
  const columns: ColumnsType<TopicItem> = [
    {
      title: '排序',
      dataIndex: 'sort_order',
      key: 'sort_order',
      width: 80,
      render: (order: number) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <DragOutlined style={{ marginRight: 8, color: '#999' }} />
          {order}
        </div>
      ),
    },
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '图标',
      dataIndex: 'icon',
      key: 'icon',
      width: 100,
      render: (icon: string) => (
        icon ? (
          <div style={{ fontSize: 24, textAlign: 'center' }}>{icon}</div>
        ) : (
          <div style={{ fontSize: 12, color: '#999', textAlign: 'center' }}>无图标</div>
        )
      ),
    },
    {
      title: '主题名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
      render: (name: string, record) => (
        <div>
          <div style={{ fontWeight: 500 }}>{name}</div>
          {record.color && (
            <div style={{ 
              width: 16, 
              height: 16, 
              backgroundColor: record.color, 
              borderRadius: 2,
              marginTop: 4
            }} />
          )}
        </div>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      width: 200,
      ellipsis: true,
    },

    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: string) => (
        <Tag color={status === 'enabled' ? 'success' : 'default'}>
          {status === 'enabled' ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 搜索处理
  const onSearch = (values: SearchForm) => {
    setSearchParams(values);
    handleSearch(values);
  };

  // 重置搜索
  const onReset = () => {
    searchForm.resetFields();
    setSearchParams({});
    handleSearch({});
  };

  // 打开创建/编辑模态框
  const handleCreate = () => {
    setEditingTopic(null);
    modalForm.resetFields();
    modalForm.setFieldsValue({
      sort_order: data.length + 1,
      status: 'enabled',
    });
    setModalVisible(true);
  };

  const handleEdit = (topic: TopicItem) => {
    setEditingTopic(topic);
    modalForm.setFieldsValue({
      name: topic.name,
      description: topic.description,
      icon: topic.icon,
      color: topic.color,
      sort_order: topic.sort_order,
      status: topic.status,
    });
    setModalVisible(true);
  };

  // 提交表单
  const handleModalSubmit = async (values: TopicForm) => {
    setModalLoading(true);
    try {
      if (editingTopic) {
        // 更新主题
        await adminApi.topicManagement.adminTopicsUpdate(editingTopic.id, values);
        message.success('主题更新成功');
      } else {
        // 创建主题
        await adminApi.topicManagement.adminTopicsCreate(values);
        message.success('主题创建成功');
      }
      
      setModalVisible(false);
      refresh();
    } catch (error) {
      message.error('操作失败，请重试');
    } finally {
      setModalLoading(false);
    }
  };

  // 删除处理
  const handleDelete = (id: number) => {
    confirm({
      title: '确认删除',
      content: '确定要删除这个主题吗？删除后关联的卡片将失去此主题分类。',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          await adminApi.topicManagement.adminTopicsDelete(id);
          message.success('删除成功');
          refresh();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  return (
    <div>
      {/* 搜索表单 */}
      <Card style={{ marginBottom: 16 }}>
        <Form
          form={searchForm}
          layout="inline"
          onFinish={onSearch}
          style={{ marginBottom: 16 }}
        >
          <Row gutter={[16, 16]} style={{ width: '100%' }}>
            <Col xs={24} sm={12} md={8}>
              <Form.Item name="keyword" label="关键词">
                <Input placeholder="搜索主题名称或描述" allowClear />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} md={8}>
              <Form.Item name="status" label="状态">
                <Select placeholder="选择状态" allowClear>
                  <Option value="enabled">启用</Option>
                  <Option value="disabled">禁用</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col>
              <Space>
                <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                  搜索
                </Button>
                <Button onClick={onReset}>
                  重置
                </Button>
              </Space>
            </Col>
          </Row>
        </Form>
      </Card>

      {/* 操作按钮和表格 */}
      <Card>
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleCreate}
            >
              新建主题
            </Button>
            <Button icon={<ReloadOutlined />} onClick={refresh}>
              刷新
            </Button>
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={data}
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
          rowKey="id"
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 创建/编辑模态框 */}
      <Modal
        title={editingTopic ? '编辑主题' : '创建主题'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={modalForm}
          layout="vertical"
          onFinish={handleModalSubmit}
        >
          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item
                name="name"
                label="主题名称"
                rules={[
                  { required: true, message: '请输入主题名称' },
                  { min: 1, max: 20, message: '名称长度在1-20个字符之间' },
                ]}
              >
                <Input placeholder="请输入主题名称" />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item
                name="icon"
                label="图标"
                rules={[
                  { max: 10, message: '图标长度不能超过10个字符' },
                ]}
              >
                <Input placeholder="请输入图标（如：🍎）" />
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item
            name="description"
            label="描述"
            rules={[
              { max: 200, message: '描述长度不能超过200个字符' },
            ]}
          >
            <Input.TextArea
              rows={3}
              placeholder="请输入主题描述（可选）"
              showCount
              maxLength={200}
            />
          </Form.Item>

          <Row gutter={16}>
            <Col xs={24} md={8}>
              <Form.Item
                name="color"
                label="颜色"
                rules={[
                  { max: 20, message: '颜色值长度不能超过20个字符' },
                ]}
              >
                <Input placeholder="请输入颜色值（如：#FF5722）" />
              </Form.Item>
            </Col>
            <Col xs={24} md={8}>
              <Form.Item
                name="sort_order"
                label="排序"
                rules={[{ required: true, message: '请输入排序值' }]}
              >
                <InputNumber
                  min={1}
                  max={999}
                  style={{ width: '100%' }}
                  placeholder="排序值"
                />
              </Form.Item>
            </Col>
            <Col xs={24} md={8}>
              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: '请选择状态' }]}
              >
                <Select placeholder="请选择状态">
                  <Option value="enabled">启用</Option>
                  <Option value="disabled">禁用</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <div style={{ textAlign: 'right', marginTop: 24 }}>
            <Space>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
              <Button
                type="primary"
                htmlType="submit"
                loading={modalLoading}
              >
                {editingTopic ? '保存' : '创建'}
              </Button>
            </Space>
          </div>
        </Form>
      </Modal>
    </div>
  );
};

export default TopicList;